<template>
  <div class="home-page">
    <!-- 导航栏 -->
    <div v-if="showNavigationBar" class="navigation-bar">
      <div class="header-content" v-cloak>
        <div
          class="logo-and-menu"
          style="display:flex;align-items:center;justify-content:space-between;width: 100%;"
        >
          <div style="display:flex;flex-direction:row;justify-content:flex-start;align-items:center;">
            <img src="../assets/img/logo.png" style="height:50px;" alt="Logo" />
            <div class="logo-text" style="margin-left:10px;">
              <div>融销通</div>
              <div style="font-size:12px;margin-top:5px;color: #666;">农产品融销一体平台</div>
            </div>
          </div>
        
    
          <el-menu
            :default-active="$store.state.activeIndex"
            mode="horizontal"
            @select="handleSelect"
            background-color="transparent"
            text-color="#fff"
            active-text-color="#fff"
            class="menu-bar"
          >
            <el-menu-item index="1" class="item" @click="frontBtn">首页</el-menu-item>
            <el-menu-item index="2" class="item" @click="goodsBtn">商品货源</el-menu-item>
            <el-menu-item index="3" class="item" @click="purchaseBtn">求购需求</el-menu-item>
            <el-menu-item index="4" class="item" @click="knowledgesBtn">农业知识</el-menu-item>
            <el-menu-item index="5" class="item" @click="guideBtn">专家指导</el-menu-item>
            <el-menu-item index="6" class="item" @click="shopCartBtn">购物车</el-menu-item>
            <el-submenu index="7" class="item">
              <template #title>融资申请</template>
              <el-menu-item index="7-1" @click="smartMatchBtn">智能匹配</el-menu-item>
              <el-menu-item index="7-2" @click="financingBtn">融资申请</el-menu-item>
            </el-submenu>
          </el-menu>

          <!-- 用户信息弹出菜单 -->
          <el-popover
            placement="bottom"
            :width="320"
            trigger="click"
            popper-class="popper-user-box"
          >
            <template #reference>
              <div class="author" style="display: flex; align-items: center;">
                <el-avatar :size="30" :src="$store.state.loginUserAvatar" />
                <i class="icon el-icon-s-custom" />
                <span :style="{ color: '#333333', marginLeft: '8px' }">{{ username || '' }}</span>
                <i class="el-icon-caret-bottom" />
              </div>
            </template>
            <div class="nickname">
              <p>登录名：{{ username || '' }}</p>
              <el-tag size="small" effect="dark" class="logout2" @click="btnLogout1">编辑</el-tag>
              &emsp;&emsp;
              <el-tag size="small" effect="dark" class="logout" @click="logout">退出</el-tag>
            </div>
          </el-popover>
        </div>
      </div>
    </div>

    <!-- 仅在 /home/front 显示走马灯、地图和排名 -->
    <div v-if="isRouterAlive && $route.path === '/home/front'">
      <!-- 走马灯部分 -->
      <div class="large-carousel">
        <el-carousel :interval="4000" type="card" height="600px" style="margin: 0 auto; max-width: 95%;">
          <el-carousel-item @click.native="navigateToRoute3()">
            <img src="/R.jpg" alt="Image 1" class="carousel-image" />
          </el-carousel-item>
          <el-carousel-item @click.native="navigateToRoute2()">
            <img src="/S.jpg" alt="Image 2" class="carousel-image" />
          </el-carousel-item>
          <el-carousel-item @click.native="navigateToRoute({ id: 67 })">
            <img src="/T.jpg" alt="Image 3" class="carousel-image" />
          </el-carousel-item>
        </el-carousel>
      </div>

      <!-- 主内容区域 -->
      <div class="content">
        <!-- 中国地图展示 -->
        <div class="map-container" ref="echartsMap" @click.native="handleMapClick">
          <h3 class="map-title">
            <img src="m.jpg" alt="Wheat Icon" class="title-icon" />全国农产品销售分布图
          </h3>
          <div class="echarts-map"></div>
        </div>

        <!-- 销售排名展示 -->
        <div class="data-display">
          <h3>农产品销售排名</h3>
          <!-- 切换按钮 -->
          <el-radio-group v-model="rankingType" @change="updateChart" style="margin-bottom: 10px;">
            <el-radio-button label="sales">按销售量</el-radio-button>
            <el-radio-button label="amount">按销售额</el-radio-button>
          </el-radio-group>
          <el-table :data="sortedSalesRanking" style="width: 100%;">
            <el-table-column prop="rank" label="排名" width="80" :formatter="formatRank" />
            <el-table-column prop="province" label="省份" width="120"></el-table-column>
            <el-table-column v-if="rankingType === 'sales'" prop="sales" label="销售量 (kg)" width="120" />
            <el-table-column v-else prop="prices" label="销售额 (元)" width="120" />
          </el-table>
          <el-button type="primary" style="margin-top: 20px;">查看更多</el-button>
        </div>
      </div>
    </div>

    <!-- 弹窗 -->
    <el-dialog :visible.sync="dialogVisible" :title="dialogTitle">
      <p>{{ dialogMessage }}</p>
    </el-dialog>
  </div>
</template>
<script>
import * as echarts from 'echarts';
import { map ,line} from '@/api/address';

export default {
  data() {
    return {
      
      searchValue: '',
      showHotSearch: false, // 控制热门搜索的显示
      hotSearchList: ['苹果', '新疆哈密瓜', '樱桃'], // 热门搜索项
      activeIndex: '1',
      username: '',
      salesRanking: [],
      lineRanking: [],
      rankingType: 'sales',
      chart: null,
      isRouterAlive: true,
      dialogVisible: false,
      dialogTitle: '',
      dialogMessage: '',
      showNavigationBar: true, // 控制导航栏显示
      provinceMap: {
        '北京': '北京市',
        '天津': '天津市',
        '上海': '上海市',
        '重庆': '重庆市',
        '河北': '河北省',
        '山西': '山西省',
        '辽宁': '辽宁省',
        '吉林': '吉林省',
        '黑龙江': '黑龙江省',
        '江苏': '江苏省',
        '浙江': '浙江省',
        '安徽': '安徽省',
        '福建': '福建省',
        '江西': '江西省',
        '山东': '山东省',
        '河南': '河南省',
        '湖北': '湖北省',
        '湖南': '湖南省',
        '广东': '广东省',
        '广西': '广西壮族自治区',
        '海南': '海南省',
        '四川': '四川省',
        '贵州': '贵州省',
        '云南': '云南省',
        '陕西': '陕西省',
        '甘肃': '甘肃省',
        '青海': '青海省',
        '内蒙古': '内蒙古自治区',
        '西藏': '西藏自治区',
        '宁夏': '宁夏回族自治区',
        '新疆': '新疆维吾尔自治区',
        '香港': '香港特别行政区',
        '澳门': '澳门特别行政区',
        '台湾': '台湾省',
      },
      geoCoordMap: {
        '北京市': [116.40, 39.90],
        '天津市': [117.20, 39.13],
        '上海市': [121.47, 31.23],
        '重庆市': [106.55, 29.57],
        '河北省': [114.48, 38.03],
        '山西省': [112.55, 37.87],
        '辽宁省': [123.43, 41.80],
        '吉林省': [125.32, 43.90],
        '黑龙江省': [126.63, 45.75],
        '江苏省': [118.78, 32.04],
        '浙江省': [120.15, 30.28],
        '安徽省': [117.28, 31.86],
        '福建省': [119.30, 26.08],
        '江西省': [115.89, 28.68],
        '山东省': [117.00, 36.67],
        '河南省': [113.62, 34.75],
        '湖北省': [114.30, 30.60],
        '湖南省': [112.93, 28.23],
        '广东省': [113.23, 23.16],
        '广西壮族自治区': [108.33, 22.82],
        '海南省': [110.35, 20.02],
        '四川省': [104.07, 30.67],
        '贵州省': [106.71, 26.57],
        '云南省': [102.71, 25.04],
        '陕西省': [108.95, 34.27],
        '甘肃省': [103.82, 36.07],
        '青海省': [101.78, 36.62],
        '内蒙古自治区': [111.67, 40.82],
        '西藏自治区': [91.13, 29.65],
        '宁夏回族自治区': [106.23, 38.49],
        '新疆维吾尔自治区': [87.62, 43.82],
        '香港特别行政区': [114.17, 22.32],
        '澳门特别行政区': [113.54, 22.20],
        '台湾省': [121.52, 25.03],
      },
    };
  },
  computed: {
    sortedSalesRanking() {
      return this.salesRanking
        .sort((a, b) => {
          if (this.rankingType === 'sales') {
            return b.sales - a.sales;
          }
          return b.prices - a.prices;
        })
        .map((item, index) => ({
          ...item,
          rank: index + 1,
        }));
    },
  },
  methods: {
    handleSearch() {
      this.$emit('search', this.searchValue);
    },
    handleSearchItemClick(item) {
      this.searchValue = item;
      this.handleSearch();
    },
    setSearchValue(value) {
      this.searchValue = value;
    },
    hideHotSearch() {
      // 延时隐藏以防止点击热门搜索项时直接隐藏
      setTimeout(() => {
        this.showHotSearch = false;
      }, 200);
    },
    handleSelect(key) {
      this.$store.commit('updateActiveIndex', key); // 更新 Vuex 中的 activeIndex
    },
    frontBtn() {
      this.$store.commit('updateActiveIndex', '1');
      this.$router.push('/home/front').catch((err) => err);
    },
    goodsBtn() {
      this.$store.commit('updateActiveIndex', '2');
      this.$router.push('/home/goods').catch((err) => err);
    },
    purchaseBtn() {
      this.$store.commit('updateActiveIndex', '3');
      this.$router.push('/home/purchase').catch((err) => err);
    },
    knowledgesBtn() {
      this.$store.commit('updateActiveIndex', '4');
      this.$router.push('/home/knowledge').catch((err) => err);
    },
    guideBtn() {
      this.$store.commit('updateActiveIndex', '5');
      this.$router.push('/home/guide').catch((err) => err);
    },
    shopCartBtn() {
      this.$store.commit('updateActiveIndex', '6');
      this.$router.push('/home/shopcart').catch((err) => err);
    },
    smartMatchBtn() {
      this.$store.commit('updateActiveIndex', '7-1');
      this.$router.push('/home/smartMatch').catch((err) => err);
    },
    financingBtn() {
      this.$store.commit('updateActiveIndex', '7-2');
      this.$router.push('/home/financing').catch((err) => err);
    },
    navigateToRoute(params) {
      this.activeIndex = '2';
      console.log(this.activeIndex);
      this.$router.push({
        path: '/home/details',
        query: { orderId: params.id },
      });
    },
    navigateToRoute2() {
      this.activeIndex = '4';
      console.log(this.activeIndex);
      this.$router.push({
        path: '/home/knowledge/22',
      });
    },
    navigateToRoute3() {
      this.activeIndex = '4';
      console.log(this.activeIndex);
      this.$router.push({
        path: '/home/knowledge/26',
      });
    },
    formatRank(row) {
      const rank = row.rank;
      if (rank === 1) return '🥇';
      if (rank === 2) return '🥈';
      if (rank === 3) return '🥉';
      return rank;
    },
    async initChart() {
      if (this.chart) {
        this.chart.dispose();
      }
      this.chart = echarts.init(this.$refs.echartsMap.querySelector('.echarts-map'));
      try {
        const response = await fetch(
          'https://geo.datav.aliyun.com/areas_v3/bound/geojson?code=100000_full'
        );
        const chinaJson = await response.json();
        echarts.registerMap('china', chinaJson);

        this.updateChart(); // 初始化时更新地图

        window.addEventListener('resize', this.resizeChart);
      } catch (error) {
        console.error('无法加载中国地图数据:', error);
      }
    },
    updateChart() {
  if (!this.chart) return;

  // 标准化省份名称：使用 provinceMap 映射排行榜数据
  const data = this.sortedSalesRanking.map((item) => {
    const standardizedProvince = this.provinceMap[item.province] || item.province; // 使用映射标准化名称
    return {
      name: standardizedProvince,
      sales: item.sales,
      prices: item.prices,
      rank: item.rank,
    };
  });

  // 获取前三名数据用于显示奖牌和数据
  const topThree = data
    .filter((item) => item.rank <= 3)
    .map((item) => {
      const coord = this.geoCoordMap[item.name];
      return coord
        ? { name: item.name, value: [...coord, item.sales, item.prices], rank: item.rank, sales: item.sales, prices: item.prices }
        : null;
    })
    .filter((item) => item !== null);

  // 设置地图上显示省份名称和奖牌
  const labelFormatter = (params) => {
    const rank = params.data?.rank;
    const label = params.name; // 恢复各个省份显示省份名称
    if (rank === 1) return `${label} 🥇`;
    if (rank === 2) return `${label} 🥈`;
    if (rank === 3) return `${label} 🥉`;
    return label; // 恢复所有省份的名称显示
  };

  // 创建地图和省份销售数据的配置
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: (params) => {
        if (params.seriesType === 'lines') {
          // 显示物流路线的 tooltip
          return `${params.data.fromName} -> ${params.data.toName}<br/>货物流动量: ${params.data.value}`;
        } else {
          // 显示省份的 tooltip，修复前三名的数据问题
          const data = params.data || {};
          const sales = data.sales || '0';
          const prices = data.prices || '0';
          return `${params.name}<br/>销售量: ${sales} kg<br/>销售额: ${prices} 元`;
        }
      },
    },
    visualMap: {
      min: 0,
      max: Math.max(...data.map((d) => (this.rankingType === 'sales' ? d.sales : d.prices))) || 100,
      left: 'left',
      top: 'bottom',
      text: ['高', '低'],
      inRange: {
        color: ['#e0f3e2', '#4a7c59'], // 使用更柔和的蓝绿色渐变
      },
      show: true,
    },
    geo: {
      map: 'china',
      roam: true, // 保持可缩放和可拖动
      layoutCenter: ['50%', '75%'], // 向下移动50%
      layoutSize: '100%', // 填满容器
      label: {
        show: true,
        formatter: labelFormatter, // 恢复省份名称显示
        position: 'inside',
        fontSize: 12,
      },
      itemStyle: {
        normal: {
          borderColor: '#88b377',
          areaColor: '#e0f3e2',
          shadowColor: 'rgba(0, 0, 0, 0.5)',
          shadowBlur: 10,
        },
        emphasis: {
          areaColor: '#d4f2d0',
        },
      },
    },
    series: [
      {
        name: '农产品销售',
        type: 'map',
        geoIndex: 0,
        data: data.map((d) => ({
          name: d.name,
          value: this.rankingType === 'sales' ? d.sales : d.prices,
          sales: d.sales,
          prices: d.prices,
          rank: d.rank,
        })),
        label: {
          show: true,
          formatter: labelFormatter, // 恢复省份名称显示
        },
      },
      // 显示前三名的特殊标记
      {
        name: 'Top 3',
        type: 'effectScatter',
        coordinateSystem: 'geo',
        data: topThree,
        symbolSize: 20,
        showEffectOn: 'render',
        rippleEffect: {
          brushType: 'stroke',
        },
        label: {
          show: true,
          formatter: labelFormatter, // 前三名恢复显示省份名称
          position: 'right',
          color: '#000',
          fontSize: 14,
          fontWeight: 'bold',
          backgroundColor: '#fff',
          borderRadius: 4,
          padding: [3, 5],
          borderWidth: 1,
          borderColor: '#aaa',
        },
        itemStyle: {
          color: '#f4e925',
          shadowBlur: 10,
          shadowColor: '#333',
        },
      },
    ],
  };

  // 从后端获取的路线数据
  const routeData = this.lineRanking;

  // 将物流数据转换为 ECharts 需要的格式
  const linesData = routeData.map((item) => {
    const fromCoord = this.geoCoordMap[this.provinceMap[item.from] || item.from];
    const toCoord = this.geoCoordMap[this.provinceMap[item.to] || item.to];
    return fromCoord && toCoord
      ? {
          fromName: item.from,
          toName: item.to,
          coords: [fromCoord, toCoord],
          value: item.quantity,
        }
      : null;
  }).filter((item) => item !== null);

  // 添加物流路线的 series，**固定颜色为深绿色**
  const logisticsSeries = {
    name: '物流路线',
    type: 'lines',
    coordinateSystem: 'geo',
    zlevel: 2,
    effect: {
      show: true,
      period: 6, // 轨迹动画的速度
      trailLength: 0.7,
      color: '#005500', // **固定颜色为深绿色**
      symbolSize: 3, // 轨迹点大小
    },
    lineStyle: {
      color: '#005500', // **固定颜色为深绿色**
      width: 2,
      opacity: 0.6,
      curveness: 0.2, // 曲线的弯曲程度
    },
    data: linesData, // 物流路线数据
  };

  // 起点和终点：使用统一的标记样式（不显示省份名称）
  const scatterStartEnd = linesData.flatMap(item => [
    {
      name: item.fromName,
      value: this.geoCoordMap[this.provinceMap[item.fromName] || item.fromName],
      symbol: 'diamond', // 使用菱形标记
      symbolSize: 10,
      itemStyle: { color: '#666666' }, // 统一灰色标记
      label: { show: false }, // 不显示省份名称
    },
    {
      name: item.toName,
      value: this.geoCoordMap[this.provinceMap[item.toName] || item.toName],
      symbol: 'diamond', // 使用菱形标记
      symbolSize: 10,
      itemStyle: { color: '#666666' }, // 统一灰色标记
      label: { show: false }, // 不显示省份名称
    }
  ]);

  // 效果标记起点和终点
  const scatterEffect = {
    name: '物流起点终点',
    type: 'effectScatter',
    coordinateSystem: 'geo',
    data: scatterStartEnd,
    symbolSize: 12,
    rippleEffect: {
      brushType: 'stroke',
    },
    label: {
      show: false, // 不显示起点终点的标签
    },
    itemStyle: {
      color: '#666666', // 统一的灰色标记
    },
  };

  // 将物流路线和起点终点 scatter 加入到 series 中
  option.series.push(logisticsSeries, scatterEffect);

  // 更新图表
  this.chart.setOption(option);
}

,
    showProvinceDetail(province, event) {
      const data = this.salesRanking.find((item) => {
        const standardizedProvince = this.provinceMap[item.province] || item.province;
        return standardizedProvince === province;
      });

      const content = data
        ? `${province}<br/>销售量: ${data.sales}kg<br/>销售额: ${data.prices}元`
        : `${province}<br/>无数据`;

      this.chart.setOption({
        graphic: [
          {
            type: 'group',
            left: event.offsetX,
            top: event.offsetY,
            children: [
              {
                type: 'line',
                left: 0,
                top: 0,
                shape: {
                  x1: 0,
                  y1: 0,
                  x2: 50,
                  y2: -50,
                },
                style: {
                  stroke: '#555',
                },
              },
              {
                type: 'rect',
                left: 55,
                top: -70,
                shape: {
                  width: 120,
                  height: 60,
                },
                style: {
                  fill: '#fff',
                  stroke: '#333',
                  shadowBlur: 8,
                  shadowColor: 'rgba(0,0,0,0.3)',
                },
              },
              {
                type: 'text',
                left: 65,
                top: -60,
                style: {
                  text: content,
                  fill: '#333',
                  font: '14px Arial',
                },
              },
            ],
          },
        ],
      });
    },
    resizeChart() {
      if (this.chart) {
        this.chart.resize();
      }
    },
    handleSelect(key, keyPath) {
      this.activeIndex = key;
    },
   
    logout() {
      this.$store.commit('updateLoginUserNickname', '');
      this.$store.commit('removeStorage');
      this.$router.push('/login').catch((err) => err);
    },
    btnLogout1() {
      this.$router.push('/home/user').catch((err) => err);
    },
  },
  watch: {
    activeIndex(newIndex) {
      if (newIndex === '1') {
        this.$nextTick(() => {
          this.initChart();
        });
      }
    },
    $route(to) {
      this.isRouterAlive = to.path === '/home/front';
      this.showNavigationBar = to.path !== '/login'; // 如果是 /login 页面，不显示导航栏
    },
  },
  created() {
    map()
      .then((response) => {
        this.salesRanking = response.data.map((item) => ({
          province: item.province,
          sales: item.sales,
          prices: item.prices,
        }));
        if (this.activeIndex === '1') {
          this.initChart();
        }
      })
      .catch((error) => {
        console.error('Error adding address:', error);
      });
      line()
      .then((response) => {
        console.log("GGGGGGGGGGG",response);
        this.lineRanking= response.data.map((item) => ({
          from: item.from,
          to: item.to,
          quantity: item.quantity,
        }));

        if (this.activeIndex === '1') {
          this.initChart();
        }
      })
      .catch((error) => {
        console.error('Error adding address:', error);
      });
    this.$store.commit('updateActiveIndex', '1');

    const storedUser = localStorage.getItem('user');
    if (storedUser) {
      this.username = storedUser;
    }
  },
};
</script>

<style lang="less" scoped>
.home-page {
  padding: 20px;
  background-color: transparent;
  .content {
    display: flex;
    justify-content: space-between;
    margin-top: 20px;
    background-color: transparent;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  }
  .map-container {
    width: 65%;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    background-color: #fff;
    position: relative;
    .echarts-map {
      width: 100%;
      height: 600px;
    }
    .title-icon {
      width: 20px;
      height: 20px;
      margin-right: 10px;
    }
    .map-title {
      position: absolute;
      top: 10px;
      left: 50%;
      transform: translateX(-50%);
      font-size: 18px;
      font-weight: bold;
      color: #333;
      background: rgba(255, 255, 255, 0.8);
      padding: 5px 10px;
      border-radius: 5px;
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    }
  }
  .data-display {
    width: 30%;
    padding: 20px;
    border: 1px solid #ddd;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    background-color: #fff;
  }
  .large-carousel {
    margin: 50px auto;
    max-width: 95%;
    box-shadow: 0px 4px 20px rgba(0, 0, 0, 0.1);
    border-radius: 10px;
    background-color: transparent;
  }
  .el-carousel__item {
    background-color: transparent !important;
    cursor: pointer;
  }
  .carousel-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  .el-carousel__item h3 {
    color: #475669;
    opacity: 0.75;
    line-height: 600px;
    margin: 0;
    text-align: center;
  }
  .el-submenu__title,
  .el-menu--popup {
    background-color: #ffffff !important;
    border: 1px solid #ddd;
    color: #333;
  }
  .el-menu--popup .el-menu-item {
    color: #333 !important;
  }
}
.navigation-bar {
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 1000;
  .header-content {
    background: linear-gradient(90deg, #7fbf4d, #f7e463);
    padding: 0 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #ddd;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
}
.menu-bar .item {
  display: flex;
  align-items: center;
  height: 50px;
  padding: 0 15px;
  transition: background-color 0.3s ease;
}
.menu-bar .item:hover {
  background-color: rgba(255, 255, 255, 0.1);
}
.author {
  display: flex;
  align-items: center;
  padding: 5px 10px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 20px;
  transition: background 0.3s ease;
}
.author:hover {
  background: rgba(255, 255, 255, 1);
}
.search-input {
  margin-left: 20px;
  width: 300px;
}
.search-icon {
  cursor: pointer;
  margin-left: 10px;
}
.hot-search-dropdown {
  position: absolute;
  top: 40px;
  left: 180px;
  z-index: 1000;
  width: 300px;
}
</style>
